using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Department;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace B.S.NewMedical.Api.Write.Controllers.ContentManagement.Department
{
    /// <summary>
    /// 科室管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class DepartmentController : ControllerBase
    {
        private readonly IMediator _mediator;

        public DepartmentController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        /// <summary>
        /// 新增一级科室
        /// </summary>
        /// <param name="command">新增科室命令</param>
        /// <returns>新增的科室ID</returns>
        /// <remarks>
        /// 创建一级科室，ParetId自动设置为0
        /// </remarks>
        [HttpPost]
        public async Task<IActionResult> AddFirstLevelDepartment([FromBody] AddDepartmentCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                // 确保创建的是一级科室
                command.ParetId = 0;

                var result = await _mediator.Send(command);
                return Ok(new { Id = result, Message = "一级科室创建成功" });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "创建一级科室时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 新增二级科室
        /// </summary>
        /// <param name="parentId">父级科室ID</param>
        /// <param name="command">新增科室命令</param>
        /// <returns>新增的科室ID</returns>
        /// <remarks>
        /// 在指定的一级科室下创建二级科室
        /// </remarks>
        [HttpPost]
        public async Task<IActionResult> AddSecondLevelDepartment(int parentId, [FromBody] AddDepartmentCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                if (parentId <= 0)
                {
                    return BadRequest(new { Message = "父级科室ID必须大于0" });
                }

                // 设置父级科室ID
                command.ParetId = parentId;

                var result = await _mediator.Send(command);
                return Ok(new { Id = result, Message = "二级科室创建成功", ParentId = parentId });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "创建二级科室时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 新增科室（通用接口）
        /// </summary>
        /// <param name="command">新增科室命令</param>
        /// <returns>新增的科室ID</returns>
        /// <remarks>
        /// 通用新增接口，通过ParetId区分一级科室(0)和二级科室(>0)
        /// </remarks>
        [HttpPost]
        public async Task<IActionResult> AddDepartment([FromBody] AddDepartmentCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);
                var departmentType = command.ParetId == 0 ? "一级科室" : "二级科室";
                return Ok(new { Id = result, Message = $"{departmentType}创建成功", ParentId = command.ParetId });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "创建科室时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 更新科室
        /// </summary>
        /// <param name="command">更新科室命令</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<IActionResult> UpdateDepartment([FromBody] UpdateDepartmentCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);
                if (result)
                {
                    return Ok(new { Message = "科室更新成功" });
                }
                else
                {
                    return NotFound(new { Message = "科室不存在或已被删除" });
                }
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "更新科室时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除科室
        /// </summary>
        /// <param name="command">批量删除命令</param>
        /// <returns>批量删除结果</returns>
        /// <remarks>
        /// 注意：如果科室有下级科室，将无法删除
        /// </remarks>
        [HttpDelete]
        public async Task<IActionResult> DeleteDepartments([FromBody] DeleteDepartmentCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);

                if (result.Success)
                {
                    return Ok(new
                    {
                        result.Message,
                        result.SuccessCount,
                        result.FailCount,
                        result.FailedIds
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        result.Message,
                        result.SuccessCount,
                        result.FailCount,
                        result.FailedIds
                    });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "批量删除科室时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 删除单个科室
        /// </summary>
        /// <param name="id">科室ID</param>
        /// <param name="updatePeople">操作人</param>
        /// <returns>删除结果</returns>
        /// <remarks>
        /// 注意：如果科室有下级科室，将无法删除
        /// </remarks>
        [HttpDelete]
        public async Task<IActionResult> DeleteByIdDepartment(int id, [FromQuery] string? updatePeople = null)
        {
            try
            {
                if (id <= 0)
                {
                    return BadRequest(new { Message = "科室ID必须大于0" });
                }

                var command = new DeleteDepartmentCommand
                {
                    Ids = new List<int> { id },
                    UpdatePeople = updatePeople
                };

                var result = await _mediator.Send(command);

                if (result.Success && result.SuccessCount > 0)
                {
                    return Ok(new { Message = "科室删除成功" });
                }
                else
                {
                    if (result.FailedIds.Contains(id))
                    {
                        return BadRequest(new { Message = "科室删除失败，可能存在下级科室或科室不存在" });
                    }
                    else
                    {
                        return NotFound(new { Message = "科室不存在或删除失败" });
                    }
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "删除科室时发生错误", Error = ex.Message });
            }
        }
    }
}